<template>
  <div class="example">
    <a-spin tip="进入系统中 . . ." />
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { currentPost, currentpermissions, getToken, getUserInfo, refreshToken } from '../../api/modules/login/login'
import { decrypt, encrypt } from '../../utils/crypto'

const route = useRoute()
const router = useRouter()

const md = location.search.split('&')[0].slice(4)

const { password, username } = JSON.parse(decrypt(md))
const { key, routerUrl, setOfBookId, title } = route.query
localStorage.setItem('selectModule', JSON.stringify({ key, routerUrl, title }))

// 获取用户信息
async function getUserInfoApi() {
  const userInfos = await getUserInfo()
  localStorage.setItem('userInfos', JSON.stringify(userInfos))
  const res = await currentpermissions()

  localStorage.setItem('AccessData', JSON.stringify(res.groups))
}

// 获取token
getToken({
  password,
  userName: username,
  clientId: 'admin-client-demo',
  clientSecret: '1q2w3e*',
  remember: true,
  mode: 'none'
}).then(async res => {
  localStorage.setItem('token', res.access_token)
  localStorage.setItem('refresh_token', res.refresh_token)
  localStorage.setItem('loginForm', encrypt(JSON.stringify({ password, username })))

  if (res.access_token) {
    await getUserInfoApi()
    if (setOfBookId) {
      await currentPost(setOfBookId)
      // 刷新token
      const refreshTokenData = await refreshToken({
        refreshToken: res.refresh_token,
        clientId: 'admin-client-demo',
        clientSecret: '1q2w3e*'
      })
      localStorage.setItem('token', refreshTokenData.access_token)
      localStorage.setItem('refresh_token', refreshTokenData.refresh_token)
    }

    // router.replace(routerUrl);
    // 默认跳转首页
    router.replace('/home')
  }
})
</script>

<style scoped>
.example {
  display: flex;
  justify-content: center;
  text-align: center;
  background: rgba(0, 0, 0, 0.05);
  height: 100vh;
}
.ant-spin-spinning {
  position: fixed;
  top: 50%;
  margin-top: -24px;
}
</style>
